<?php
session_start();
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Account Controller
 * @package  CMS
 * @author Vui Nguyen - 09/04/2013 
 * @link http://joomlavui.info
 */
class Doanhnghiep extends CI_Controller {
    
    protected $_arrParam;
    
    protected $_per_page = 12;
    
    function __construct() {
        parent::__construct();
        $this->load->library('session');
		$this->load->library('smarty3');
        $this->load->library('pagination');
		$this->smarty = new CI_Smarty3();
        // load models user,billing
        $this->load->model('kpay/db_user_model');
        $this->db_user_model = new db_user_model();
        $this->load->model('kpay/db_card_model');
        $this->db_card_model = new db_card_model();
	    $this->load->library('pay/login_service');
        
        require_once APPPATH . '../library/captcha/securimage.php';
        
        $this->smarty->assign('menu','doanhnghiep');
        
        $this->_arrParam = $_REQUEST;
    }

    // ------------------------- HOME -------------------------------------
    function index() {
        $user = $this->session->userdata('user_info');
        if(!$user)
        {
            redirect('account/login');
        }
        
        $this->smarty->assign('user_info',$user);
        $this->smarty->assign('menu_dn','account');
        $this->smarty->view('template/pages_live/doanhnghiep/01_info','dn_content');
        $this->smarty->view('template/pages_live/doanhnghiep/01_doanhnghiep','content');
        $this->smarty->display('template/frontend_live/home');
    }
    
    //------------------------ REGISTER -----------------------
    function register(){
        //$this->smarty->view('template/pages_live/doanhnghiep/01_info','dn_content');
        $this->smarty->view('template/pages_live/doanhnghiep/01_register','content');
        $this->smarty->display('template/frontend_live/home');
    }
    
    //------------------------ TRANS PASSWORD -----------------------
    function trans_pass()
    {
        $user = $this->session->userdata('user_info');
        if(!$user)
        {
            redirect('account/login');
        }
        
        //KIỂM TRA MẬT KHẨU GIAO DỊCH ĐÃ CÓ HAY CHƯA?
        $userextra = $this->db_user_model->getUserExtraByCustomerID($user[0]->customerID);
        $step = ($userextra[0]->trans_pass=="")?0:1;
        
        $this->smarty->assign(
                                array(
                                    'user_info'     => $user,
                                    'menu_dn'       => 'transpass',
                                    'step'          => $step
                                    )
                            );
        
        $this->smarty->view('template/pages_live/doanhnghiep/01_transpass','dn_content');
        $this->smarty->view('template/pages_live/doanhnghiep/01_doanhnghiep','content');
        $this->smarty->display('template/frontend_live/home');
    }
    
    //------------------------ TRANS HISTORY -----------------------
    function trans_history()
    {
        $user = $this->session->userdata('user_info');
        if(!$user)
        {
            redirect('account/login');
        }
        
        $this->smarty->assign('menu_dn','transhistory');
        $this->smarty->assign('user_info', $user);
        $this->smarty->view('template/pages_live/doanhnghiep/01_transhistory','dn_content');
        $this->smarty->view('template/pages_live/doanhnghiep/01_doanhnghiep','content');
        $this->smarty->display('template/frontend_live/home');
    }
    
    //---------------------- PERMISSION MEMBERS ------------------------------
    function trans_history_detail()
    {
        $user = $this->session->userdata('user_info');
        if(!$user)
        {
            redirect('account/login');
        }
        
        $this->smarty->assign('menu_dn','account');
        $this->smarty->assign('user_info', $user);
        $this->smarty->view('template/pages_live/doanhnghiep/01_transhistorydetail','dn_content');
        $this->smarty->view('template/pages_live/doanhnghiep/01_doanhnghiep','content');
        $this->smarty->display('template/frontend_live/home');
        
    }
    
    //---------------------- CHANGE TYPE ACCOUNT ----------------------
    function change_account_type()
    {
        $user = $this->session->userdata('user_info');
        if(!$user)
        {
            redirect('account/login');
        }
        
        $this->smarty->assign('menu_dn','changeacctype');
        $this->smarty->assign('user_info', $user);
        $this->smarty->view('template/pages_live/doanhnghiep/01_change_account_type','dn_content');
        $this->smarty->view('template/pages_live/doanhnghiep/01_doanhnghiep','content');
        $this->smarty->display('template/frontend_live/home');
    }
    
    //---------------------- MEMBER LIST ------------------------------
    function members()
    {
        $user = $this->session->userdata('user_info');
        if(!$user)
        {
            redirect('account/login');
        }
        
        $config['base_url'] = base_url(). "doanhnghiep/grid_members";
        $config['total_rows'] = $this->db_user_model->count_row($user[0]->uID)->num_rows();
        $limit = $config['per_page'] = $this->_per_page;
        $start = $this->uri->segment(3);
        $config['uri_segment'] = 3;
        $config["num_links"] = 3;    
        
        $this->pagination->initialize($config);

        $data['pagination'] = $this->pagination->create_links();
        $data['member'] = $this->db_user_model->getListUserByIdParentPager($user[0]->uID, $limit, $start);
        $this->smarty->assign('data',$data);
        $this->smarty->assign('menu_dn','members');
        $this->smarty->assign('user_info', $user);
        $this->smarty->view('template/pages_live/doanhnghiep/01_member','dn_content');
        $this->smarty->view('template/pages_live/doanhnghiep/01_doanhnghiep','content');
        $this->smarty->display('template/frontend_live/home');
    }
    
    //---------------------- MEMBER LIST PAGINATION AJAX ------------------------------
    function grid_members(){
        if(IS_AJAX){
            $user = $this->session->userdata('user_info');
            $config['base_url'] = base_url(). "doanhnghiep/grid_members";
            $config['total_rows'] = $this->db_user_model->count_row($user[0]->uID)->num_rows();
            $limit = $config['per_page'] = $this->_per_page;
            $start = $this->uri->segment(3);
            $config['uri_segment'] = 3;
            $config["num_links"] = 3;   
            
            $this->pagination->initialize($config);
    
            $data['pagination'] = $this->pagination->create_links();
            $data['member'] = $this->db_user_model->getListUserByIdParentPager($user[0]->uID, $limit, $start);
            $this->smarty->assign('data', $data);
            $this->smarty->display('template/ajax/01_gridmember');
        }
    }
    
    //---------------------- MEMBER CHANGE STATUS ------------------------------
    function ChangeStatusUserIdParent(){
        if(IS_AJAX){
            if($this->_arrParam['type'] == 1){
                echo 1;
            }else{
                echo 0;
            }
            $this->db_user_model->ChangeStatusUserByIdParent($this->_arrParam);
        }
    }
    
    //---------------------- MEMBER DETAIL ------------------------------
    function detail_member(){
        $user = $this->session->userdata('user_info'); 
        if(!$user){
            redirect('account/login');
        }
        
        $id = $this->uri->segment(3);        
        $data = $this->db_user_model->getDetailUserByIdParent($user[0]->uID, $id);
        
        if(count($data)>0){
            $exproviderID = explode(",",$data->providerID);
            $providerName = array();
            foreach($exproviderID as $key => $value){
                $providers = $this->db_user_model->getCardProvider($value);
                foreach($providers as $item){
                    $providerName[] = $item->providerName;
                }
            }
            
            $exfnID = explode(",",$data->fID);
            $fnNametitle = array();
            foreach($exfnID as $key => $val){
                $fnName = $this->db_user_model->getFunctionName($val);
                foreach($fnName as $items){
                    $fnNametitle[] = $items->title;
                }
            }
            $from['providerName'] = $providerName;
            $from['functionName'] = $fnNametitle;
            $this->smarty->assign('from',$from);
        }
        $data_custom['uid_detail'] = $id;        
        $this->smarty->assign('data',$data);
        $this->smarty->assign('data_custom',$data_custom); // custom
        $this->smarty->assign('menu_dn','members');
        $this->smarty->assign('user_info', $user);
        $this->smarty->view('template/pages_live/doanhnghiep/01_detailmember','dn_content');
        $this->smarty->view('template/pages_live/doanhnghiep/01_doanhnghiep','content');
        $this->smarty->display('template/frontend_live/home');
    }
    
    //---------------------- FILTER MEMBER -----------------------------
    function filterMember(){
        
        $user = $this->session->userdata('user_info');
        if(!$user){
            redirect('account/login');
        }
        
        if(IS_AJAX){
            $data['member'] = $this->db_user_model->searchMember($user[0]->uID, $this->_arrParam);
            $this->smarty->assign('data', $data);
            $this->smarty->display('template/ajax/01_gridmember_search');
        }
    }
    
    //---------------------- ADD MEMBER -----------------------------
    function add_members(){
        $user = $this->session->userdata('user_info');
        if(!$user)
        {
            redirect('account/login');
        }  
        $this->smarty->assign('user_info', $user);
        $this->smarty->assign('menu_dn','addmember');
        $this->smarty->view('template/pages_live/doanhnghiep/01_addmember','dn_content');
        $this->smarty->view('template/pages_live/doanhnghiep/01_doanhnghiep','content');
        $this->smarty->display("template/frontend_live/home");
    }
    
    //---------------------- PERMISSION MEMBERS ------------------------------
    // SHOW FOMR PHAN QUYEN
    function permission_members($uidFunctionList=NULL){        
        ///
        $data   = "";
        $fname_options          = array();
        $fname_options_actived  = "";  
        $provider_options       = array();
        $provider_options_actived  = "";  
        $user = $this->session->userdata('user_info');
        if(!$user)
        {
            redirect('account/login');
        }        
        ///
        $data_child = $this->db_user_model->getDetailUserByIdParent($user[0]->uID, $uidFunctionList);
        if($data_child){
            $fname_string       = "'".str_replace(",","','",$data_child->fID)."'";            
        }
        //echo $data_child->fID;
        //print_r($data_child);exit;
        // load user of doanh nghiep
        $data['member']     = $this->db_user_model->getListUserByIdParent($user[0]->uID);        
        // load function name user of doanh nghiep
        $data['fname']      = $this->db_user_model->getFuntionName($groupID=1); // group doanh nghiep        
        if($data['fname']){
            $fname_options[""]  = "[---Chọn hình thức---]";            
            foreach($data['fname'] as $tmp){
                $fname_options[$tmp->fnID]=$tmp->title;
            }            
            //$fname_options_actived = $xxx; // just test
            //$fname_options_actived = array('1','2'); // just test
            //print_r($fname_options_actived);
            //echo "<td>" . form_dropdown('name1', $fname_options, $fname_options_actived,'id="category" multiple ') . "</td>";
            $data['fname_options']              = $fname_options;
            $data['fname_options_actived']      = $fname_options_actived;
        }
        // provider 
        $data['provider'] = $this->db_user_model->getCardProviders($catID=8); // card dien thoai
        if($data['provider']){
            $provider_options[""]  = "[---Chọn nhà cung cấp---]";
            foreach($data['provider'] as $tmp){
                $provider_options[$tmp->providerID]=$tmp->providerName;
            }  
            //$provider_options_actived = array("1");// just test
            $data['provider_options']              = $provider_options;
            $data['provider_options_actived']      = $provider_options_actived;
        }
        //print_r($data['member']);exit;        
        //
        $this->smarty->assign('data',$data);        
        $this->smarty->assign('menu_dn','permissionmember');
        $this->smarty->assign('user_info', $user);
        $this->smarty->view('template/pages_live/doanhnghiep/01_permissionmember','dn_content');
        $this->smarty->view('template/pages_live/doanhnghiep/01_doanhnghiep','content');
        $this->smarty->display('template/frontend_live/home');
        
    }    
    // UPDATE PHAN QUYEN USER
    function permission_members_update(){
        //	
        $msgs	= array();
        $msg	= "";
        $code 	= -1;
        $user   = $this->session->userdata('user_info');
        if(!$user){
            $code 		= -1;
            $msgs[]             = "Phiên giao dịch của bạn đã hết.";
            $data['uidParent']  = "";
        }else{
            $data['uidParent'] 		= $user[0]->uID;
        } 
        // POST VALUE        
        $data['emailChild'] 		= $this->input->post('emailChild');          
        $data['fID']                    = $this->input->post('fID');// list chuc nang
        $data['providerID']		= $this->input->post('providerID'); // list nha cung cap
        $data['moneyLimit']		= $this->input->post('moneyLimit');
        $data['phoneRegister']		= $this->input->post('phoneRegister');
        $data['captcha']		= $this->input->post('captcha');
        //
        $data['ip']                     = get_real_ip();
	$data['updated'] 		= date("Y-m-d H:i:s");        
        ////// CHECK VALID POST        
        // check code
        $securimage = new Securimage();
        if(!$securimage->check($data['captcha'])){
            $code 		= -1;
            $msg[] = 'Mã xác nhận không đúng';
        }
        // check valid post
        if(!$data['emailChild']){
            $code 		= -1;
            $msg[]              = 'Vui lòng nhập Email.';
        }
        if(!$data['fID'] or $data['fID'][0]==""){
            $code 		= -1;
            $msg[]              = 'Vui lòng chọn hình thức sử dụng.';
        }
        if(!$data['providerID']){
            $code 		= -1;
            $msg[]              = 'Vui lòng chọn tên nhà cung cấp';
        }
        if(!$data['moneyLimit']){
            $code 		= -1;
            $msg[]              = 'Vui lòng nhập số tiền tối đa sử dụng';
        }
        if(!$data['phoneRegister']){
            $code 		= -1;
            $msg[]              = 'Vui lòng nhập số điện thoại đăng ký';
        }
        //        
        $i=0;
        if($data['fID'] or $data['fID'][0]!=""){
            $max_items      = count($data['fID']);
            foreach ($data['fID'] as $temp) 
            {					 
                if(($i+1)<$max_items)
                    $data['fID'] 		.= $temp.',';
                else
                    $data['fID'] 		.= $temp;
                $i++;
            }
            $data['fID']    = str_replace("Array","", $data['fID']);
        }
        /// 
        $i=0;
        if($data['providerID']){            
            $max_items      = count($data['providerID']);
            foreach ($data['providerID'] as $temp) 
            {					 
                if(($i+1)<$max_items)
                    $data['providerID'] 		.= $temp.',';
                else
                    $data['providerID'] 		.= $temp;
                $i++;
            }
            $data['providerID']    = str_replace("Array","", $data['providerID']);
        }        
        // check ma nha cung cap xem co hop le hay ko?
//        $tmp1				= $this->db_user_model->checkCardProvider($data['providerID']);
//        if(!$tmp1){
//            $code 		= -1;
//            $msgs[] 	= "Thông tin nhà cung cấp không hợp lệ.";
//        }                
        // check tai khoan ton tai trong he thong hay ko
        $tmp2				= $this->db_user_model->checkEmail($data['emailChild']);    
        // CHECK SO TIEN DOANH NGHIEP CO CON DU DE PHAN QUYEN HAY KO?
        //print_r($tmp2);exit;
        if(!$tmp2){
            $code 		= -1;
            $msgs[]             = "Thông tin tài khoản không hợp lệ hoặc không tồn tại.";
        }else{    
            // Get user by Email
            $userChild		= $this->db_user_model->getUserByEmail($data['emailChild']);
            if($userChild){
                $data['uIDChild'] 		= $userChild[0]->uID;
                // check tai khoan co thuoc quyen quan ly cua doanh nghiep hay ko?        
                $tmp3           = $this->db_user_model->checkUserBelongDoanhNghiep($data['uIDChild'],$data['uidParent']);
                if(!$tmp3){
                    $code 		= -1;
                    $msgs[] 	= "Tài khoản không thuộc danh sách thành viên.";
                } 
            }
        }
        //echo count($msgs);
        //print_r($msgs);exit;
        if(!count($msgs)) { 
            // E1.SAVE LOG KHỞI TẠO GIAO DỊCH TRƯỚC KHI ĐĂNG NHẬP VÀO EPAY
            $aParamCardLog=array(                                                            
                            'fID'                   => $data['fID'],
                            'providerID'            => $data['providerID'],
                            'moneyLimit'            => $data['moneyLimit'],                        
                            'phoneRegister'         => $data['phoneRegister'],                                                
                            'updated'               => $data['updated'],
                            'ip'                    => $data['ip']
            );                     
            
            try {
                // change hamf nafy // check 2 dieu kien uid va uidparent de update.
                $log1 		= $this->db_user_model->update_FuntionListUser($data,$aParamCardLog); //ok
                $code 		= 1;
                $msgs[]             = "Thêm thành viên thành công.";
            } catch (Exception $exc) {
                //echo $exc->getTraceAsString();
                $code 		= -1;
                $msgs[]             = "Lỗi hệ thống, vui lòng liên hệ bộ phận hỗ trợ để biết thêm chi tiết";
            }            
            // END - E1.SAU KHI NẠP THẺ LẬP TỨC KHỞI TẠO LOG GIAO DỊCH CHO DÙ SAI HAY ĐÚNG.
        }
        foreach ($msgs as $m){
            //$msg.=str_replace("Array","", $m)."<br/>";
            $msg.=$m."<br/>";
        }
        $msg	= json_encode(array("code"=>$code,"msg"=>$msg));
        echo $msg;//exit;
    }
    // CHECK MEMBER VALID
    function permission_members_check(){
        //	
        $msgs	= array();
        $msg	= "";
        $code 	= -1; 
        $user   = $this->session->userdata('user_info');
        if(!$user){
            $code 		= -1;
            $msgs[] 	= "Phiên giao dịch của bạn đã hết.";
            $data['uidParent']          = "";
        }else{
            $data['uidParent'] 		= $user[0]->uID;
        }
        // CHECK VALUE
        $data['emailChild'] 		= $this->input->post('emailChild');          
        // check tai khoan ton tai trong he thong hay ko
        $tmp2				= $this->db_user_model->checkEmail($data['emailChild']);        
        //print_r($tmp2);exit;
        if(!$tmp2){
            $code 		= -1;
            $msgs[]             = "Thông tin tài khoản không hợp lệ hoặc không tồn tại.";
        }else{    
            // Get user by Email
            $userChild		= $this->db_user_model->getUserByEmail($data['emailChild']);
            if($userChild){
                $data['uIDChild'] 		= $userChild[0]->uID;
                // check tai khoan co thuoc quyen quan ly cua doanh nghiep hay ko?        
                $tmp3           = $this->db_user_model->checkUserBelongDoanhNghiep($data['uIDChild'],$data['uidParent']);
                if(!$tmp3){
                    $code 		= -1;
                    $msgs[] 	= "Tài khoản không thuộc danh sách thành viên.";
                } 
            }
        }    
        if(!count($msgs)) { 
             $code 		= 1;
            $msgs[]             = "Tài khoản hợp lệ.";
        }
        foreach ($msgs as $m){
                $msg.="$m<br/>";			
        }
        $msg	= json_encode(array("code"=>$code,"msg"=>$msg));
        echo $msg;//exit;
    }
}

/* End of file account.php */
/* Location: ./application/controllers/account.php */